package teshop.web;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import teshop.service.CustomerService;


@SuppressWarnings("serial")
@Component("customerLogon")
@Scope("request")
public class CustomerLogon implements Serializable {

	private CustomerService service;

	private String login;

	private String password;

	@Autowired
	public CustomerLogon(CustomerService service) {
		this.service = service;
	}

	/**
	 * Perform authorize action
	 */
	public String authorize() {
		boolean isUser = service.authorize(login, password);
		if (isUser)
			printSuccessMessage();
		else
			printFailMessage();
		return null;
	}

	/**
	 * Prints message that authorization completed successfully
	 */
	private void printSuccessMessage() {
		FacesMessage facesMessage = new FacesMessage(
				FacesMessage.SEVERITY_INFO, "You have logged in successfully",
				"OK");
		FacesContext.getCurrentInstance().addMessage(null, facesMessage);
	}

	/**
	 * Prints message that authorization failed
	 */	
	private void printFailMessage() {
		FacesMessage facesMessage = new FacesMessage(
				FacesMessage.SEVERITY_ERROR,
				"Authorization failed. Incorrect login or password", "OK");
		FacesContext.getCurrentInstance().addMessage(null, facesMessage);
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
